package com.richapp.launcher.database.infrared.dao;

import android.content.Context;
import android.util.Log;

import com.j256.ormlite.dao.Dao;
import com.j256.ormlite.stmt.DeleteBuilder;
import com.j256.ormlite.stmt.QueryBuilder;
import com.j256.ormlite.stmt.Where;
import com.richapp.launcher.database.infrared.InfraredDatabaseHelper;
import com.richapp.launcher.database.infrared.mode.Button;

import java.util.List;

public class ButtonDao {

	private Context context;
	private InfraredDatabaseHelper helper = null;
	private Dao<Button,Integer> dao = null;

	public ButtonDao(Context context) {
		this.context = context;
		try {
			helper = InfraredDatabaseHelper.getHelper(this.context);
            dao = helper.getDao(Button.class);
            dao.setObjectCache(false);
		} catch (Exception e) {
			Log.e("error", e.getMessage());
		}
	}

    public List<Button> getButtonTemplete(int machineTypeId){
        List<Button> list = null;
        try{
            QueryBuilder qb = dao.queryBuilder();
            qb.where().eq("machineTypeId",machineTypeId);
            qb.orderBy("disCh",false);
            list = qb.query();
        }catch (Exception e){
            Log.e("error", e.getMessage());
        }
        return list;
    }

    public Button getButton(int machineTypeId ,String buttonName){
        Button button = null;
        try{
            Where where = dao.queryBuilder().where();
            where.and(where.eq("machineTypeId", machineTypeId), where.or(where.eq("disCh", buttonName), where.eq("disEn", buttonName), where.eq("note", buttonName)));
            Object obj = where.queryForFirst();
            if(obj instanceof Button){
                button = (Button)obj;
            }
        }catch (Exception e){
            Log.e("error", e.getMessage());
        }
        return button;
    }

    public Button getButton(int buttonId){
        Button button = null;
        try{
            Where where = dao.queryBuilder().where();
            where.eq("buttonId",buttonId);
            Object obj = where.queryForFirst();
            if(obj instanceof Button){
                button = (Button)obj;
            }
        }catch (Exception e){
            Log.e("error", e.getMessage());
        }
        return button;
    }

    public void add(Button button){
        try{
            dao.createOrUpdate(button);
        }catch (Exception e){
            Log.e("error", e.getMessage());
        }
    }

    public void deleteAll(){
        try{
            DeleteBuilder deleteBuilder = dao.deleteBuilder();
            deleteBuilder.delete();
        }catch (Exception e){
            Log.e("error", e.getMessage());
        }
    }

}
